import {Component, OnInit, TemplateRef} from '@angular/core';
import {NzModalRef, NzModalService} from 'ng-zorro-antd';
import {Router} from '@angular/router';

@Component({
  selector: 'app-cross-border',
  templateUrl: './cross-border.component.html',
  styleUrls: ['./cross-border.component.sass']
})
export class CrossBorderComponent {

  tplModal: NzModalRef;

  tplWindow: Window;

  constructor(private modalService: NzModalService, private router: Router) {}

  createTplModal(tplTitle: TemplateRef<{}>, tplContent: TemplateRef<{}>, tplFooter: TemplateRef<{}>): void {
    this.tplModal = this.modalService.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: tplFooter,
      nzMaskClosable: false,
      nzWidth: 1024,
      nzClosable: true,
      nzOnOk: () => console.log('Click ok')
    });
    this.addCallbackEvent();
  }

  toOpenWindow(): void {
    debugger;
    this.addCallbackEvent();
    this.tplWindow = window.open('form', '_blank', 'width=1000, height=600, left=100, top=100, resizeable=yes');
  }

  openWindow(): void {
    this.addCallbackEvent();
    this.tplWindow = window.open('form', '_blank', 'width=1000, height=600, left=100, top=100, resizeable=yes');
  }

  addCallbackEvent(): void {
    debugger;
    // 响应事件
    window.addEventListener('message', (event) => {
      debugger;
      if (event.origin !== 'http://localhost:4201') {
        return;
      }
      console.log('document message received:  ' + event.data, event);
      if (this.tplModal !== null) {
        this.tplModal.destroy();
      } else if (this.tplWindow !== null) {
        this.tplWindow.close();
      }
      if (event.data === 'ack') {
        this.router.navigateByUrl('ack');
      } else if (event.data === 'error') {
        this.router.navigateByUrl('error');
      }
    }, false);
  }

  detectLinkStatus(event): void {
    debugger;
    if (event.origin !== 'http://localhost:4201') {
      return;
    }
    console.log('document message received:  ' + event.data, event);
    this.tplModal.destroy();
  }

  closeModal() {

  }
}
